package org.example.backend.demos.web.volunteerModule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.backend.demos.web.ManagementModule.dao.ProjectDao;
import org.example.backend.demos.web.volunteerModule.dao.VolunteerDao;
import org.example.backend.demos.web.volunteerModule.entity.Volunteer;
import org.example.backend.demos.web.volunteerModule.entity.VolunteerDTO;
import org.example.backend.demos.web.volunteerModule.entity.VolunteerQuery;
import org.example.backend.demos.web.volunteerModule.service.VolunteerService;
import org.example.backend.demos.web.volunteerModule.service.VolunteerStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class VolunteerServiceImpl extends ServiceImpl<VolunteerDao, Volunteer>
        implements VolunteerService {
    @Autowired
    private ProjectDao projectDao;
    @Autowired
    private VolunteerDao volunteerDao;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional
    public Volunteer submitApplication(VolunteerDTO volunteerDTO, Long userId,String name) {
        // 检查是否已报名
        if (hasApplied(userId, volunteerDTO.getProjectId())) {
            throw new RuntimeException("您已报名该项目，请勿重复报名");
        }
        String selectName = projectDao.select_name(volunteerDTO.getProjectId());
        Volunteer volunteer = new Volunteer();
        volunteer.setUserId(userId);
        volunteer.setProjectId(volunteerDTO.getProjectId());
        volunteer.setRealName(volunteerDTO.getRealName());
        volunteer.setPhone(volunteerDTO.getPhone());
        volunteer.setStatus(0); // 待审核状态
        volunteer.setApplyTime(LocalDateTime.now().format(formatter));
        volunteer.setUsername(name);
        volunteer.setProjectName(selectName);
        volunteerDao.insert(volunteer);
        return volunteer;
    }

    @Override
    public Page<Volunteer> getUserApplications(Long userId, Integer page, Integer size, Integer status) {
        Page<Volunteer> pageParam = new Page<>(page, size);
        return volunteerDao.selectUserApplications(pageParam, userId, status);
    }

    @Override
    public Volunteer getApplicationDetail(Long id, Long userId) {
        Volunteer volunteer = volunteerDao.selectApplicationDetail(id);
        if (volunteer == null) {
            throw new RuntimeException("报名记录不存在");
        }

        // 普通用户只能查看自己的申请
        if (!volunteer.getUserId().equals(userId)) {
            throw new RuntimeException("无权查看该申请");
        }

        return volunteer;
    }

    @Override
    public Page<Volunteer> getAdminApplicationList(VolunteerQuery query) {
        Page<Volunteer> pageParam = new Page<>(query.getPage(), query.getSize());
        return volunteerDao.selectAdminApplicationList(pageParam, query);
    }

    @Override
    @Transactional
    public void auditApplication(Long id, Integer status, String auditRemark) {
        Volunteer volunteer = volunteerDao.selectById(id);
        if (volunteer == null) {
            throw new RuntimeException("报名记录不存在");
        }

        if (volunteer.getStatus() != 0) {
            throw new RuntimeException("该申请已审核，无法重复操作");
        }

        String auditTime = LocalDateTime.now().format(formatter);
        int result = volunteerDao.updateAuditStatus(id, status, auditRemark, auditTime);

        if (result == 0) {
            throw new RuntimeException("审核失败");
        }
    }

    /**
     *
     * @param applicationIds 志愿者ID
     * @param status    状态码
     * @param auditRemark
     * @return 响应数
     */
    @Override
    @Transactional
    public BatchAuditResult batchAuditApplications(List<Long> applicationIds, Integer status, String auditRemark) {
        int successCount = 0;
        int failCount = 0;

        for (Long applicationId : applicationIds) {
            try {
                auditApplication(applicationId, status, auditRemark);
                successCount++;
            } catch (Exception e) {
                failCount++;
                System.err.println("审核申请 " + applicationId + " 失败: " + e.getMessage());
            }
        }

        return new BatchAuditResult(successCount, failCount);
    }

    @Override
    public boolean hasApplied(Long userId, Long projectId) {
        return volunteerDao.existsByUserAndProject(userId, projectId);
    }

    @Override
    public VolunteerStats getVolunteerStats() {
        QueryWrapper<Volunteer> wrapper = new QueryWrapper<>();

        Long totalApplications = volunteerDao.selectCount(wrapper);

        wrapper.clear();
        wrapper.eq("status", 0);
        Long pendingCount = volunteerDao.selectCount(wrapper);

        wrapper.clear();
        wrapper.eq("status", 1);
        Long approvedCount = volunteerDao.selectCount(wrapper);

        wrapper.clear();
        wrapper.eq("status", 2);
        Long rejectedCount = volunteerDao.selectCount(wrapper);

        return new VolunteerStats(totalApplications, pendingCount, approvedCount, rejectedCount);
    }
}